package com.atguigu.tingshu.live.api;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.live.util.WebSocketLocalContainerUtil;
import com.atguigu.tingshu.model.live.FromUser;
import com.atguigu.tingshu.model.live.SocketMsg;
import com.atguigu.tingshu.model.user.UserInfo;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;

/**
 * Author  王东剑
 * Created on 28/6/2024 PM6:31
 * Package_name com.atguigu.tingshu.live.api
 * Description
 */
@Slf4j
@Controller
@ServerEndpoint(value = "/api/websocket/{liveRoomId}/{token}")
public class WebSocketApiController {
	private static StringRedisTemplate redisTemplate;
	@Autowired
	private void setRedisTemplate(StringRedisTemplate redisTemplate){
		WebSocketApiController.redisTemplate = redisTemplate;
	}
	@OnOpen
	public void onOpen(Session session, @PathParam("liveRoomId") Long liveRoomId, @PathParam("token") String token){
		String userInfoJSON = redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX.concat(token));
		if(StringUtils.isEmpty(userInfoJSON)) return;
		UserInfo userInfo = JSON.parseObject(userInfoJSON, UserInfo.class);
		Long userId = userInfo.getId();
		FromUser fromUser = new FromUser();
		fromUser.setUserId(userId);
		fromUser.setNickname(userInfo.getNickname());
		fromUser.setAvatarUrl(userInfo.getAvatarUrl());


		WebSocketLocalContainerUtil.addFromUser(userId,fromUser);
		WebSocketLocalContainerUtil.addSession(userId,session);
		WebSocketLocalContainerUtil.addUserIdToLiveRoom(liveRoomId,userId);

		WebSocketLocalContainerUtil.sendMsg(
				WebSocketLocalContainerUtil.buildSocketMsg(
						liveRoomId,
						fromUser,
						SocketMsg.MsgTypeEnum.JOIN_CHAT,
						userInfo.getNickname().concat(" 加入直播间!")));
	}
	@OnClose
	public void onClose(Session session, @PathParam("liveRoomId") Long liveRoomId, @PathParam("token") String token){
		String userInfoJSON = redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX.concat(token));
		if(StringUtils.isEmpty(userInfoJSON)) return;
		UserInfo userInfo = JSON.parseObject(userInfoJSON, UserInfo.class);
		Long userId = userInfo.getId();
		FromUser fromUser = new FromUser();
		fromUser.setUserId(userId);
		fromUser.setNickname(userInfo.getNickname());
		fromUser.setAvatarUrl(userInfo.getAvatarUrl());


		WebSocketLocalContainerUtil.removeFromUser(userId);
		WebSocketLocalContainerUtil.removeSession(userId);
		WebSocketLocalContainerUtil.removeUserIdToLiveRoom(liveRoomId,userId);

		WebSocketLocalContainerUtil.sendMsg(
				WebSocketLocalContainerUtil.buildSocketMsg(
						liveRoomId,
						fromUser,
						SocketMsg.MsgTypeEnum.CLOSE_SOCKET,
						userInfo.getNickname().concat(" 退出直播间!")));
	}
	@OnError
	public void onError(Session session, Throwable throwable){
		throwable.printStackTrace();
	}
	@OnMessage
	public void onMessage(Session session, String msg){
		if (StringUtils.isEmpty(msg)) return;
		SocketMsg socketMsg = JSON.parseObject(msg, SocketMsg.class);
		WebSocketLocalContainerUtil.sendMsg(socketMsg);
	}
}
